package com.lyh.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyh.common.annotation.Log;
import com.lyh.common.core.controller.BaseController;
import com.lyh.common.core.domain.AjaxResult;
import com.lyh.common.core.domain.entity.SysUser;
import com.lyh.common.core.page.TableDataInfo;
import com.lyh.common.enums.BusinessType;
import com.lyh.common.enums.GoodsSortRuleEnum;
import com.lyh.common.utils.CommonUtils;
import com.lyh.common.utils.SecurityUtils;
import com.lyh.common.utils.poi.ExcelUtil;
import com.lyh.system.domain.Goods;
import com.lyh.system.domain.GoodsSpec;
import com.lyh.system.domain.ReceiveAddress;
import com.lyh.system.domain.req.GoodsEditReq;
import com.lyh.system.domain.req.GoodsPubilshReq;
import com.lyh.system.domain.req.GoodsReq;
import com.lyh.system.domain.req.MemberPurchaseInfoPageReq;
import com.lyh.system.domain.resp.GoodsDetailResp;
import com.lyh.system.domain.resp.MemberPurchaseInfoResp;
import com.lyh.system.domain.vo.BuyGoodsVo;
import com.lyh.system.domain.vo.GoodsVo;
import com.lyh.system.domain.vo.PlaceOrderVo;
import com.lyh.system.mapper.GoodsMapper;
import com.lyh.system.mapper.GoodsSpecMapper;
import com.lyh.system.mapper.ReceiveAddressMapper;
import com.lyh.system.service.IGoodsService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * 商品Controller
 *
 * @author ruoyi
 * @date 2023-04-27
 */
@RestController
@RequestMapping("/app/goods")
public class GoodsController extends BaseController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private GoodsSpecMapper goodsSpecMapper;
    @Autowired
    private ReceiveAddressMapper receiveAddressMapper;

    /**
     * 查询商品列表
     */
//    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(required = false) String type, @RequestParam(required = false) String sortRule,
                           @RequestParam(required = false) Integer goodsClass, @RequestParam(required = false) String goodsClassType,
                           @RequestParam(required = false) String goodsName) {
        List<Goods> list = goodsMapper.selectGoodsByGoodsClass(goodsClass, type, sortRule, goodsClassType, goodsName);
        return AjaxResult.success(list);
    }

    @ApiOperation("商品管理-后台分页")
    @ApiImplicitParam(name = "goodsClass", value = "商品类型 1 普通 2门店 3其他", required = false, dataType = "int", dataTypeClass = Integer.class)
    @GetMapping("/webList")
    public TableDataInfo webList(GoodsReq req) {
        startPage();
        List<Goods> list = goodsService.selectWebGoods(req);
        return getDataTable(list);
    }

    @Log(title = "商品管理导出", businessType = BusinessType.EXPORT)
    @ApiOperation("商品管理导出")
    @PostMapping("/export")
    public void  export(HttpServletResponse response, @RequestBody GoodsReq req)
    {
        req.setPageNum(null);
        req.setPageSize(null);
        List<Goods> list = goodsService.selectWebGoods(req);
        ExcelUtil<Goods> util = new ExcelUtil<>(Goods.class);
        util.exportExcel(response, list, "商品管理导出");
    }

    /**
     * 修改商品
     */
    @ApiOperation("商品管理-后台编辑")
    @PostMapping("/edit")
    public AjaxResult editProducy(@Validated @RequestBody GoodsEditReq req) {
        return toAjax(goodsService.editGoods(req));
    }

    /**
     * 下单前
     */
    @PostMapping("/placeOrder")
    public AjaxResult placeOrder(@RequestBody BuyGoodsVo bgv) {
        Long id = bgv.getId();
        Long num = bgv.getNum();
        if (id == null || num == null) {
            throw new RuntimeException("商品id和数量不能为空！");
        }
        PlaceOrderVo placeOrderVo = new PlaceOrderVo();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        GoodsSpec goodsSpec = goodsSpecMapper.selectById(bgv.getSpecId());
        Goods goods = goodsMapper.selectById(id);
        BeanUtils.copyProperties(goods, placeOrderVo);
        placeOrderVo.setAllPrice(goods.getPrice().multiply(new BigDecimal(num)));
        placeOrderVo.setPrice(goods.getPrice());
        placeOrderVo.setNum(bgv.getNum());

        if (goodsSpec != null) {
            placeOrderVo.setGoodsSpecs("颜色：" + goodsSpec.getColor() + ",尺寸：" + goodsSpec.getSize());
        }
        ReceiveAddress receiveAddress;
        receiveAddress = receiveAddressMapper.selectOne(new LambdaQueryWrapper<ReceiveAddress>()
                .eq(ReceiveAddress::getIsDefault, 1)
                .eq(ReceiveAddress::getUserId, user.getUserId()));
        placeOrderVo.setReceiveAddress(receiveAddress);
        if (receiveAddress == null) {
            List<ReceiveAddress> receiveAddresses = receiveAddressMapper.selectList(new LambdaQueryWrapper<ReceiveAddress>()
                    .orderByDesc(ReceiveAddress::getCreateTime)
                    .eq(ReceiveAddress::getUserId, user.getUserId()));
            placeOrderVo.setReceiveAddress(receiveAddresses.size() > 0 ? receiveAddresses.get(0) : null);
        }
        return AjaxResult.success(placeOrderVo);
    }

    /**
     * 删除商品
     */
    @ApiOperation("商品管理-删除")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(goodsService.deleteGoodsByIds(ids));
    }


    /**
     * 获取商品详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        GoodsVo goodsVo = goodsService.selectGoodsById(id);
        List<GoodsSpec> goodsSpecs = goodsSpecMapper.selectList(new LambdaQueryWrapper<GoodsSpec>()
                .eq(GoodsSpec::getGoods_id, id));
        goodsVo.setGoodsSpecs(goodsSpecs);
        return success(goodsVo);
    }

    /*    *//**
     * 导出商品列表
     *//*
    @PreAuthorize("@ss.hasPermi('system:goods:export')")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Goods goods)
    {
        List<Goods> list = goodsService.selectGoodsList(goods);
        ExcelUtil<Goods> util = new ExcelUtil<Goods>(Goods.class);
        util.exportExcel(response, list, "商品数据");
    }

    *//**
     * 获取商品详细信息
     *//*
    @PreAuthorize("@ss.hasPermi('system:goods:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(goodsService.selectGoodsById(id));
    }

    *//**
     * 新增商品
     *//*
    @PreAuthorize("@ss.hasPermi('system:goods:add')")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Goods goods)
    {
        return toAjax(goodsService.insertGoods(goods));
    }

    *//**
     * 修改商品
     *//*
    @PreAuthorize("@ss.hasPermi('system:goods:edit')")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Goods goods)
    {
        return toAjax(goodsService.updateGoods(goods));
    }*/

    /**
     * 修改商品
     */
    @ApiOperation("商品管理-商品发布保存")
    @PostMapping("/publishGoods")
    public AjaxResult publishGoods(@Validated @RequestBody GoodsPubilshReq req) {
        return toAjax(goodsService.publishGoods(req));
    }

    /**
     * 修改商品
     */
    @ApiOperation("商品管理-商品发布上架")
    @PostMapping("/publishShelfGoods")
    public AjaxResult publishShelfGoods(@Validated @RequestBody GoodsPubilshReq req) {
        return toAjax(goodsService.publishShelfGoods(req));
    }


    @ApiOperation("商品管理-商品发布删除")
    @DeleteMapping("/publishGoodsDelete/{id}")
    public AjaxResult publishGoodsDelete(@PathVariable Long id) {
        return toAjax(goodsService.publishGoodsDelete(id));
    }


    @ApiOperation("商品管理-获取商品详细信息")
    @GetMapping(value = "/goods/{id}")
    public AjaxResult<GoodsDetailResp> getGoodsInfp(@PathVariable("id") Long id) {
        return success(goodsService.getGoodsPublish(id));
    }

}
